package com.ingesup.controllers
{
	import com.ingesup.entities.LettreType;
	import com.ingesup.models.AppModel;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	public class LettreTypeController
	{
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		public var lettreSrv:RemoteObject;
		
		public function LettreTypeController()
		{
		}
		
		[EventHandler (event="com.ingesup.events.LettreTypeEvent.GET_ALL")]
		public function getAll ():void 
		{
			serviceHelper.executeServiceCall(lettreSrv.getListLettre(),
				
				function handleGetAllResult(event:ResultEvent):void
				{
					AppModel.listeLettres = event.result as ArrayCollection;
				},
				
				function handleGetAllFault(event:FaultEvent):void 
				{
					Alert.show(event.fault.message + " " + event.fault.faultDetail);
				}
			);
		}
		
		
		[EventHandler (event="com.ingesup.events.LettreTypeEvent.MODIFIER", properties="lettreType")]
		public function update (dataToUpdate:LettreType):void 
		{
			serviceHelper.executeServiceCall(lettreSrv.updateLettreType(dataToUpdate),
				
				function handleGetAllResult(event:ResultEvent):void
				{
					//AppModel.lettreCourante = null;
				},
				
				function handleGetAllFault(event:FaultEvent):void 
				{
					Alert.show(event.fault.message + " " + event.fault.faultDetail);
				}
			);
		}
		
		[EventHandler (event="com.ingesup.events.LettreTypeEvent.ENREGISTRER", properties="lettreType")]
		public function save (dataToSave:LettreType):void 
		{	
			serviceHelper.executeServiceCall(lettreSrv.createLettreType(dataToSave),
				
				function handleSaveResult(event:ResultEvent):void 
				{
					AppModel.listeLettres.addItem(event.result as LettreType);
					AppModel.listeLettres.refresh();
					//AppModel.lettreCourante = null;
				},
				
				function handleSaveFault(event:FaultEvent):void 
				{
					trace("ERROR: "+event.fault.message);
				}
			);
		}
		
		
		[EventHandler (event="com.ingesup.events.LettreTypeEvent.SUPPRIMER", properties="lettreType")]
		public function remove (dataToRemove:LettreType):void 
		{
			var indexDataToRemove:int = AppModel.listeLettres.getItemIndex(dataToRemove);
			
			serviceHelper.executeServiceCall(lettreSrv.deleteLettreType(dataToRemove),
				
				function handleRemoveResult(event:ResultEvent, indexDataToRemove:int):void 
				{
					AppModel.listeLettres.removeItemAt(indexDataToRemove);
				},
				
				function handleRemoveFault(event:FaultEvent):void 
				{
					trace("ERROR: "+event.fault.message);
				},
				[indexDataToRemove]
			);
		}
	}
}